import axios from "./request";
const common = "/api/v1.0/common"; //公共
import store from '@/store'
import router from '../router'
import {
	deleteChildren, convertKey
} from '@/library'
import jwt_decode from "jwt-decode";

export function getLandYearValues(params){
	return axios.get('rbac/data/getLandYearValues',{
		params
	})
}

/**
 * 获取关联主体
 * params
 * @returns 
 */
export function subjectData(params){
	let url = "";
	return axios.get(url, { params })
}


/**
 * 查看采集界面的详细信息
 * @param {*} params 
 */

 export function getCollectTaskLand(params) {
	let url = "rbac/data/CollectTaskLand/list";
	return axios.get(url, { params })
}


/**
 * 农产品分类
 * @param {*} pageNumber
 * @param {*} pageSize
 * @returns
 */
export function getlandProduct(params) {
	return axios.get(`baseinfo/api/v1.0/fishing/landTypep/productType/getList`, { params })
}



/**
 * 主体类别
 * @param {*} pageNumber
 * @param {*} pageSize
 * @returns
 */
export function getLandType(params) {
	return axios.get(`baseinfo/api/v1.0/fishing/landType/selectAll`, { params })
}


/**
 * 主体信息查询
 * @param {*} pageNumber
 * @param {*} pageSize
 * @returns
 */
export function getSubjectInfoList(params) {
	return axios.get(`rbac/data/subject/getSubjectInfoList`, { params })
}

/**
 * @name 查询图斑状态
 * @param {*} file
 * @returns {Promise}
 */
export function listPart(params) {
	let url = 'rbac/data/collectTaskLand/listPart';
	return axios.get(url, {
		params
	})
}

export function municipality(pid) {
	return axios.get('baseinfo/v1.0/adminstrative/getByPid', {
		params: {
			pid
		}
	})
}

// export function town(pid) {
// 	return axios.get('baseinfo/v1.0/adminstrative/getByPid', {
// 		params:{
// 			pid
// 		}
// 	})
// }

/**
 * @name 获取数据字典的内容
 * @param {*} file
 * @returns {Promise}
 */
export function selectPage(params) {
	return axios.get('baseinfo/baseInfo/propertyValue/selectPage', {
		params
	})
}

/**
 * @name 公共图片上传方法
 * @param {*} file
 * @returns {Promise}
 */
export function uploadFile(file) {
	let formData = new FormData();
	formData.append("file", file);
	return axios.post(`oss/file/upload`, {
		headers: {
			"Content-Type": "multipart/form-data"
		},
		params: formData,
	});
}

/**
 * @name 公共用户文件上传方法
 * @param {*} file
 * @returns {Promise}
 */
export function uploadFiles(file) {
	let formData = new FormData();
	formData.append("file", file);
	return axios.post(`rbac/sysuser/user/excelImport`, {
		headers: {
			"Content-Type": "multipart/form-data"
		},
		params: formData,
	});
}

/**
 * @name 公共主体文件上传方法
 * @param {*} file
 * @returns {Promise}
 */
export function uploadSubjectFiles(file) {
	let formData = new FormData();
	formData.append("file", file);
	formData.append("systemType", localStorage.getItem('SYS_TYPE'));
	return axios.post(`rbac/data/subject/excelImport`, {
		headers: {
			"Content-Type": "multipart/form-data"
		},
		params: formData,
	});
}

/**
 * @name 公共登录方法
 * @param {*} file
 * @returns {Promise}
 */
export function oauthLogin(user) {
	localStorage.removeItem('userInfo');
	localStorage.removeItem('ShowMenu/setSideMenu');
	localStorage.removeItem('currentTask/setCurrentTask');
	localStorage.removeItem('vuex');
	user.scope = "all"
	// user.grant_type = "password"
	let url = "uaa/oauth/token";
	return axios.post(url, {
		params: user,
		headers: {
			Authorization: "Basic Y2xpZW50OnNlY3JldA==",
		},
	}).then((res) => {
		console.log(res);
		if (res.access_token) {
			let {
				access_token,
				userIdentity,
				administrativeCode,
				userLevel,
				loginName,
			} = res;
			let jwt = jwt_decode(access_token);
			let {
				exp,
				authorities
			} = jwt;
			let UserInfo = {
				original: res,
				token: access_token,
				authorities: authorities,
				header: exp,
				userLevel: userLevel,
				administrativeCode: administrativeCode,
				loginName: loginName,
				userName: loginName,
				UserIdentity: userIdentity[0],
			};
			localStorage.setItem("userInfo", JSON.stringify(UserInfo));
			store.dispatch("User/setAsyncUserInfo", UserInfo);

			axios.get('rbac/sys/role/get/'+userLevel)
			.then((res)=>{
				store.dispatch('User/setAsyncUserRouter', res.data)
				// .then(()=>{
				// 	let showRouteArray = res.data.menus
				// 	let children = router.options.routes[0].children
					
				// 	let filterchildren = children.filter((item) => {
				// 		if (showRouteArray.join(',').indexOf(item.name) != -1) {
				// 			return item
				// 		}
				// 		// return item.meta.roles.includes(userInfo.userLevel);
				// 	});
				// 	this.$store.commit('ShowMenu/setShowMenu',filterchildren)
				// })
			})


			getAdministrativeList().then((res) => {
				let options = JSON.parse(JSON.stringify(res.data.treeItem, ['administrativeName', 'administrativeCode', 'children']));
				options = convertKey(options, {
					'administrativeName': 'label',
					'administrativeCode': 'value'
				})
				options = deleteChildren(options)
				localStorage.setItem('getTreeData/setAsyncVillageData', JSON.stringify(options))
				store.dispatch('getTreeData/setAsyncVillageData')
			});
		}
		return Promise.resolve(res)
	})
}
/***
 * @name 获取角色列表
 */

export function RolePermission(searchForm = {
}) {
	return axios.get(`/rbac/sys/role/list`, {
		params: {
			keywords: searchForm.roleName,
			pageNum: searchForm.pageNumber,
			pageSize: searchForm.pageSize
		}
	});
}
/***
 * @name 增加角色信息
 */

export function addRole(addRoleForm) {
	return axios.post(`${common}/role/add`, {
		params: addRoleForm,
	});
}
/***
 * @name 编辑角色信息
 */
export function putRole(addRoleForm) {
	return axios.post(`${common}/role/put`, {
		params: addRoleForm,
	});
}

/**
 * 获取所有的村镇
 * @param {*}
 * @returns
 */
export function getAdministrativeList() {
	// // return axios.get(`/baseinfo/v1.0/getTreeData`).then((res) => {
	// // 	console.log(333333333333,res)
	// // 	return Promise.resolve(res)
	// // })
	// let url = '/getTreeData.json'
	// return fetch(url)
	// 	.then(response => response.json())
	// 	.then(json => {
	// 		console.log(json)
	// 		return Promise.resolve(json)
	// 	})

	return axios.get("baseinfo/v1.0/adminstrative/getAll").
		then((response) => {
			var areas = response.data;
			// console.log(areas.length);
			var areaArr01 = new Array();
			var areaArr02 = new Array();
			//重构数据
			for (var i = 0; i < areas.length; i++) {
				if (areas[i].administrativeLevel == "2") {
					areaArr01.push(areas[i]);
				}
				if (areas[i].administrativeLevel == "3") {
					areaArr01[0]["children"] = new Array();
					areaArr01[0].children.push(areas[i]);
					areaArr01[0]["children"][0]["children"] = new Array();
				}
				if (areas[i].administrativeLevel == "4") {
					areaArr01[0].children[0].children.push(areas[i]);
					var len = areaArr01[0].children[0].children.length;
					areaArr01[0]["children"][0]["children"][len - 1]["children"] = new Array();
				}
				if (areas[i].administrativeLevel == "5") {
					var administrativeHigh = areas[i].administrativeHigh;
					areaArr02 = areaArr01[0].children[0].children;
					for (var j = 0; j < areaArr02.length; j++) {
						//如果节点administrativeHigh和父节点administrativeCode相等，则push
						if (administrativeHigh == areaArr02[j].administrativeCode) {
							if (areaArr02[j].children != undefined) {
								areaArr02[j].children.push(areas[i]);
							}
						}
					}
				}
			}
			// console.log(areaArr01[0].children[0].children.length);
			// console.log(areaArr01[0].children[0]);

			let data = {
				result: "success", data: {
					treeItem: [areaArr01[0]]
				}, errorCode: "00000", errorMsg: "success"
			}

			return Promise.resolve(data)
		});
}


/**
 * 获取组织机构
 * @param {*}
 * @returns
 */
export function Organization(pageNumber = 1, pageSize = 5, searchForm = {

}) {
	return axios.get(`/rbac/sys/organ/get`, {
		params: {
			pageNumber,
			pageSize,
			organName: searchForm.organName, //组织机构
			organAddress: searchForm.organAddress, //地址
			linkMan: searchForm.linkMan, //联系人
			linkPhone: searchForm.linkPhone, //联系方式
		},
	}).then((res) => {
		return Promise.resolve(res)
	})
}


//发送认证短信
export function sendAuthCode(mobile, sendType = 1) {
	return axios
		.post(`uaa/user/sendMsg`, {
			params: {
				"sendType": sendType,
				"mobile": mobile
			},
		})
		.then((result) => {
			//console.log(result);
			// store.state.queryTasksAccordingToPlan.response = result.data;
			return Promise.resolve(result);
		});
}

//注册用户
export function registerUser(user, auth) {
	return axios
		.post(`uaa/user/register`, {
			params: {
				"mobile": user.phone,
				"msgNum": auth.validateNum,
				"tamp": auth.tamp,
				"hash": auth.hash,
				"realName": user.trueName,
				"registerCard": user.cardID,
				"password": user.password,
				"userAdministrativeCode": user.userAdministrativeCode,
				"type": 0
			},
		})
		.then((result) => {
			//console.log(result);
			// store.state.queryTasksAccordingToPlan.response = result.data;
			return Promise.resolve(result);
		});
}


//新增或编辑用户
export function createOrUpdateUser(form) {
	console.log("form", form);
	let s
	if (form.userId == "") {
		s = 'save'
	} else {
		s = 'update'
	}
	return axios
		.post(`rbac/sysuser/${s}`, {
			params: {
				'userId': form.userId || null,
				'administrativeCode': form.administrativeCode,
				'administrativeLevel': form.level,
				'username': form.account,
				'password': form.password,
				'organCode': form.organization[form.organization.length - 1],
				'registerTele': form.phone,
				'registerCard': form.registerCard,
				'realName': form.userName,
				'ids': form.roleIds.join(",")
			},
		})
		.then((result) => {
			//console.log(result);
			// store.state.queryTasksAccordingToPlan.response = result.data;
			return Promise.resolve(result);
		});
}

//查看用户详情
export function getUserDetailInfo(form) {
	return axios
		.get(`rbac/sysuser/list`, {
			params: {
				"userId": form.userId
			},
		})
		.then((result) => {
			// store.state.queryTasksAccordingToPlan.response = result.data;
			return Promise.resolve(result);
		});
}
